<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-产线`"
		width="900px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<div ref="box1" class="margin-bottom-10">
				<el-tag type="primary" effect="plain" class="margin-bottom-4">
					<span class="el-icon-tickets item-gap"></span>
					<span>基本信息</span>
				</el-tag>
				<jk-card>
					<el-row>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="产线编号" prop="code">
								<el-input v-model="ruleForm.code" placeholder="产线编号" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="产线名称" prop="name">
								<el-input v-model="ruleForm.name" placeholder="产线名称" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="清花机编号" prop="qhCode">
								<el-input v-model="ruleForm.qhCode" placeholder="清花机编号" />
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="清花机名称" prop="qhName">
								<el-input v-model="ruleForm.qhName" placeholder="清花机名称" />
							</el-form-item>
						</el-col>
						<!--<el-col :span="8">
                            <el-form-item class="margin-bottom-10" label="清花机" prop="qhId">
                                <jk-select v-model="ruleForm.qhId" size="medium" class="width-100-percent" :option-list="qhList" placeholder="清花机" />
                            </el-form-item>
                        </el-col>-->
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="区域" prop="workshopId">
								<el-select v-model="ruleForm.workshopId" class="width-100-percent" placeholder="区域" @change="onWorkshopChange">
									<el-option
										v-for="item in workshopList"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item class="margin-bottom-10" label="排序">
								<jk-number-input v-model="ruleForm.sortNum" class="width-100-percent" placeholder="排序" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item class="margin-bottom-0" label="备注">
								<el-input v-model="ruleForm.remark" type="textarea" :rows="1" placeholder="" />
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" class="margin-bottom-4">
				<jk-button size="mini" icon="el-icon-plus" :disabled="!ruleForm.workshopId" class="item-gap" type="primary" @click="onAddProcessItem">关联工序</jk-button>
			</div>
			<jk-table border :data="ruleForm.processList || []" :max-height="dialogTableHeight - 20">
				<vxe-column title="操作" align="center" field="operation" :width="110">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" icon="el-icon-plus" class="item-gap" @click="onAddProcessItem(scope.rowIndex)"></jk-button>
							<jk-button size="mini" icon="el-icon-minus" @click="onDeleteProcessItem(scope.rowIndex)"></jk-button>
						</div>
					</template>
				</vxe-column>
				<vxe-column title="工序" align="center" field="processName" :width="110">
					<template slot-scope="scope">
						<el-select v-model="scope.row.processId" placeholder="工序" size="mini">
							<el-option
								v-for="item in processList"
								:key="item.id"
								:label="item.name"
								:value="item.id"
								:disabled="ruleForm.processList.map(x => x.processId).includes(item.id)"
							></el-option>
						</el-select>
					</template>
				</vxe-column>
				<vxe-column title="机台" align="left" field="unitPrice" :min-width="110">
					<template slot-scope="scope">
						<div class="flex-start-center-wrap">
							<div
								v-for="(item, index) in scope.row.machineList"
								:key="index"
								style="padding: 2px;width: calc(100% / 6);flex-shrink: 0;"
							>
								<el-tag
									class="width-100-percent flex-between-center"
									closable
									type="info"
									@close="ruleForm.processList[scope.rowIndex].machineList.splice(index, 1)"
								>{{ item.machineName }}</el-tag>
							</div>
							<div
								style="padding: 2px;width: calc(100% / 6);flex-shrink: 0;"
							>
								<el-tag class="width-100-percent flex-center el-icon-plus" style="cursor: pointer;" @click="onAddBtn(scope)"></el-tag>
							</div>
						</div>
					</template>
				</vxe-column>
			</jk-table>
		</el-form>

		<checkbox-machine-dialog
			:default-data="editProcessItem"
			:checked-data="editProcessItem.machineList"
			check-key-name="machineId"
			:dialog-state="selectMachineDialogState"
			@on-confirm="onConfirmBtnOfSelectMachineDialog"
			@on-visible-change="onVisibleChangeOfSelectMachineDialog"
		></checkbox-machine-dialog>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import {
        ppfProductionLineCreate,
        ppfProductionLineUpdate,
        ppfProductionLineGet
    } from '../../../api/production/produtionLine';
    import checkboxMachineDialog from './components/checkbox-machine-dialog';
    import { machinemanagerMachinePage } from '../../../api/machine/machineArchives';
    export default {
        components: {
            checkboxMachineDialog },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        mixins: [calHeight],
        data() {
            return {
                editProcessIndex: null,
                editProcessItem: {},
                selectMachineDialogState: false,
                workshopList: [],
                processList: [],
                showDialog: false,
                showLoading: true,
                saveBtnLoading: false,
                ruleForm: {
                    id: null,
                    code: '',
                    qhId: '',
                    qhCode: '',
                    qhName: '',
                    name: '',
                    sortNum: 1,
                    workshopId: null,
                    workshopName: '',
                    workshopCode: '',
                    remark: '',
                    processList: [],
                    auditState: 1
                },
                rules: {
                    workshopId: [{ required: true, trigger: 'change' }],
                    qhCode: [{ required: true, trigger: 'change' }],
                    qhName: [{ required: true, trigger: 'change' }],
                    code: [{ required: true, trigger: 'change' }],
                    name: [{ required: true, trigger: 'change' }]
                },
                processItemInfo: {
                    processId: null,
                    processCode: null,
                    processName: null,
                    machineList: []
                },
                qhList: []
            };
        },
        methods: {
            onWorkshopChange() {
                this.$set(this.ruleForm, 'processList', []);
            },
            onAddProcessItem(processIndex) {
                if (processIndex || processIndex === 0) {
                    this.ruleForm.processList.splice(processIndex + 1, 0, JSON.parse(JSON.stringify(this.processItemInfo)));
                } else {
                    this.ruleForm.processList.push(JSON.parse(JSON.stringify(this.processItemInfo)));
                }
            },
            onDeleteProcessItem(processIndex) {
                this.ruleForm.processList.splice(processIndex, 1);
            },
            onVisibleChangeOfSelectMachineDialog(e) {
                this.selectMachineDialogState = e;
            },
            onConfirmBtnOfSelectMachineDialog(arr) {
                if (arr.length) {
                    this.selectMachineDialogState = false;
                    const list = this.ruleForm.processList[this.editProcessIndex].machineList ? JSON.parse(JSON.stringify(this.ruleForm.processList[this.editProcessIndex].machineList)) : [];
                    arr.forEach(x => {
                        list.push({
                            machineId: x.id,
                            machineCode: x.code,
                            machineName: x.name,
                            processId: x.processId,
                            processCode: x.processCode,
                            processName: x.processName,
                            sortNum: x.sortNum
                        });
                    });
                    list.sort((a, b) => {
                        return a.sortNum - b.sortNum;
                    });
                    this.$set(this.ruleForm.processList[this.editProcessIndex], 'machineList', list);
                }
            },
            onAddBtn(scope) {
                this.editProcessIndex = scope.rowIndex;
                this.editProcessItem = {
                    workshopId: this.ruleForm.workshopId,
                    ...JSON.parse(JSON.stringify(scope.row))
                };
                this.selectMachineDialogState = true;
            },
            getParamData() {
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                const workshopItem = this.workshopList.find(x => x.id === params.workshopId) || {};
                params.workshopCode = workshopItem.code;
                params.workshopName = workshopItem.name;
                let processItem = {};
                params.processList.forEach(item => {
                    processItem = this.processList.find(x => x.id === item.processId) || {};
                    item.processId = processItem.id;
                    item.processCode = processItem.code;
                    item.processName = processItem.name;
                });
                return params;
            },
            createAndUpdateRequest() {
                const api = !this.dataId ? ppfProductionLineCreate : ppfProductionLineUpdate;
                this.saveBtnLoading = true;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish');
                    }
                });
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return ppfProductionLineGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        const resData = res.data.res ? JSON.parse(JSON.stringify(res.data.res)) : {};
                        this.ruleForm = resData;
                    }
                });
            },
            getQhListRequest() {
                return machinemanagerMachinePage({
                    auditState: 1,
                    processCode: 'QH'
                }).then(res => {
                    if (res.data.status === 200) {
                        this.qhList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                this.processList = this.$store.state.user.userProcess.processList;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                    this.$set(this.ruleForm, 'workshopCode', this.$store.state.user.userWorkshop.defaultWorkshopCode);
                    this.$set(this.ruleForm, 'workshopName', this.$store.state.user.userWorkshop.defaultWorkshopName);
                }
                await this.getQhListRequest();
                if (this.dataId) await this.getDetailRequest();
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
<style scoped lang="scss">
</style>
